package com.scap.authen.util;

import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

public class JDate {
    private static final int[] DAYS = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    public JDate() {
    }

    
    static public String getDay() {
        Calendar voRightNow = Calendar.getInstance();
        //SystemDate
        //String strDay = Integer.toString(now.getDate());
        String vaStrDay = Integer.toString(voRightNow.get(Calendar.DAY_OF_MONTH));
        if (vaStrDay.length() == 1) {
            vaStrDay = "0" + vaStrDay;
        }
        return vaStrDay;
    }
    
    static public String getMonth() {
//        Date now = new Date(System.currentTimeMillis());
        Calendar voRightNow = Calendar.getInstance();
//        String strMonth = Integer.toString(now.getMonth()+1);
        String vaStrMonth = Integer.toString(voRightNow.get(Calendar.MONTH)+1);
        if (vaStrMonth.length() == 1) {
            vaStrMonth = "0" + vaStrMonth;
        }
        //System.out.println(strMonth);
        return vaStrMonth;
    }
    
    static public String getYear() {
        //Date now = new Date(System.currentTimeMillis());
        Calendar voRightNow = Calendar.getInstance();
        //String strYear = Integer.toString(now.getYear()+1900);
        String vaStrYear = "";
        if (voRightNow.get(Calendar.YEAR) >= 2550) { 
            vaStrYear = Integer.toString(voRightNow.get(Calendar.YEAR) - 543); 
        } else {
            vaStrYear = Integer.toString(voRightNow.get(Calendar.YEAR));
        }
        return getThaiYear(vaStrYear);
    }

    static public String getHour() {
        Calendar voRightNow = Calendar.getInstance();
        String vaStrHour = Integer.toString(voRightNow.get(Calendar.HOUR_OF_DAY));   
        if (vaStrHour.length() == 1) { vaStrHour = "0" + vaStrHour; }
        return vaStrHour;
    }

    static public String getMinutes() {
        Calendar voRightNow = Calendar.getInstance();
        String vaStrMinutes = Integer.toString(voRightNow.get(Calendar.MINUTE)); 
        if (vaStrMinutes.length() == 1) { vaStrMinutes = "0" + vaStrMinutes; }
        return vaStrMinutes;
    }

    static public String getSeconds() {
        Calendar voRightNow = Calendar.getInstance();
        String vaStrSeconds = Integer.toString(voRightNow.get(Calendar.SECOND));
        if (vaStrSeconds.length() == 1) { vaStrSeconds = "0" + vaStrSeconds; }
        return vaStrSeconds;
    }

    static public String getDate() {
        return getYear() + getMonth() + getDay();
    }

    static public String getTime() {
        return getHour() + "" + getMinutes() + "" + getSeconds();
    }

    static public long getTimeInMillis() {
        Calendar voRightNow = Calendar.getInstance();
        return voRightNow.getTimeInMillis();
    }

    static public String saveDate(String date) {
        String vaUpdateDate = "";
        String vaDd, vaMm, vaYyyy;
        try {
            if (date == null ||date.equalsIgnoreCase("")) return "";
            vaDd = date.substring(0, date.indexOf("/"));
            date = date.substring(date.indexOf("/") + 1);
            vaMm = date.substring(0, date.indexOf("/"));
            vaYyyy = date.substring(date.indexOf("/") + 1);
            vaUpdateDate = vaYyyy + String.format("%1$02d", Integer.parseInt(vaMm)) + String.format("%1$02d", Integer.parseInt(vaDd));
        }
        catch (Exception e){
        	System.out.println("saveDate Method error : "+e+" : date = "+date);
        }
        return vaUpdateDate;
    }

    static public String showDate(String paDate) {
        String vaUpdateDate = "";
        try {
            if (paDate.equals("")) return "";
            vaUpdateDate += paDate.substring(6,8)+"/";
            vaUpdateDate += paDate.substring(4,6)+"/";
            vaUpdateDate += paDate.substring(0,4);
        }
        catch(Exception e){
            e.printStackTrace();
        }
            return vaUpdateDate;
    }

    static public String saveTime(String paTime) {
        String vaUptimeTime = "";
        String vaHh, vaMm, vaSs;
        try {
            if (paTime.equals("")) return "";
            vaHh = paTime.substring(0, paTime.indexOf(":"));
            paTime = paTime.substring(paTime.indexOf(":") + 1);
            vaMm = paTime.indexOf(":") != -1 ? paTime.substring(0, paTime.indexOf(":")) : paTime.substring(0);
            vaSs = paTime.indexOf(":") == -1 ? "00" : paTime.substring(paTime.indexOf(":") + 1);
            //String a = String.format("%1$2d", mm);
            vaUptimeTime = String.format("%1$02d", Integer.parseInt(vaHh)) + String.format("%1$02d", Integer.parseInt(vaMm)) + String.format("%1$02d", Integer.parseInt(vaSs));
            //return time.substring(6, 10) + time.substring(3, 5) + time.substring(0, 2);
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return vaUptimeTime;
    }
    
    static public String showTime(String paTime) {
        String vaUpdateTime = "";
        try{
            if (paTime.equals("")) return "";
            vaUpdateTime += paTime.substring(0,2) + ":";
            vaUpdateTime += paTime.substring(2,4) + ":";
            vaUpdateTime += paTime.substring(4,6);
        }catch(Exception e){
            e.printStackTrace();
        }
        return vaUpdateTime;
    }
    
    static public String saveTimeNOColon(String paTime) {
        String vaUptimeTime = "";
        String vaHh, vaMm, vaSs;
        try {
            if(paTime.length()==8){
                vaHh = paTime.substring(0,2);
                vaMm = paTime.substring(3,5);
                return vaHh + "" + vaMm +"00";
            }else if(paTime.length() == 4){
                vaHh = paTime.substring(0,2);
                vaMm = paTime.substring(2,4);
                return vaHh + "" + vaMm +"00";
            }else{
                return paTime;
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return vaUptimeTime;
    }

    static public boolean IsWorkingDay(String paYyyy, String paMm, String paDd) {
        boolean vbRet = true;
        int vnIYear = Integer.parseInt(paYyyy);
        if (vnIYear < 2500) { vnIYear = vnIYear + 543;  }

        Calendar date = Calendar.getInstance();
        int vnDow = date.get(Calendar.DAY_OF_WEEK);
        date.clear();
        date.set(vnIYear, Integer.parseInt(paMm)-1, Integer.parseInt(paDd));
        
        vnDow = date.get(Calendar.DAY_OF_WEEK);
        String vaAaa = date.getTime().toString();
        if (date.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) { vbRet = false; }
        if (date.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { vbRet = false; }
        return vbRet;
    }
    
    private boolean isLeapYear(int pY) {
        if (pY % 400 == 0) return true;
        if (pY % 100 == 0) return false;
        return (pY % 4 == 0);
    }

    static public String getEndMonthDate(String paYear, String paMonth){
    	int[] DAYS = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    	String vT="";
    	Double vnD=0.00;
    	String[] vaTt = null;
    	vnD = ((Double.parseDouble(paYear)) - 543)/4;
    	vaTt = vnD.toString().split("[.]");
    	if(vaTt[1].equals("0")){
    		if(paMonth.equals("02")){
    			vT = "29";
    			//System.out.println("JDate="+t);
    		}else{
        		vT = ""+DAYS[Integer.parseInt(paMonth)];
    		}
    	}else{
    		if(paMonth.equals("02")){
    			vT = "28";
    			//System.out.println("JDate="+t);
    		}else{
        		vT = ""+DAYS[Integer.parseInt(paMonth)];
    		}
    	}
    	return vT;
    }

    static public String getDiffDay(String paFromDate, String paTodate, String paFromTime, String paToTime){
    	String vaDayNum = "";
    	String vaYearFrom = paFromDate.substring(0, 4);
    	String vaYearTo = paTodate.substring(0, 4);;
    	String vaMonthFrom = paFromDate.substring(4, 6);
    	String vaMonthTo = paTodate.substring(4, 6);
    	String vaDateFrom = paFromDate.substring(6, 8);
    	String vaDateTo = paTodate.substring(6, 8);
    	String vaHourFrom = paFromTime.substring(0, 2);
    	String vaHourTo = paToTime.substring(0, 2);
    	String vaMinFrom = paFromTime.substring(2, 4);
    	String vaMinTo = paToTime.substring(2, 4);
    	
    	Date voDayFrom = new GregorianCalendar(2009, 11, 01, 07, 00).getTime();
	    Date voDayTo = new GregorianCalendar(2009, 11, 02, 17, 00).getTime();
	    //Date today = new Date();

	    long voDiff = voDayTo.getTime() - voDayTo.getTime();
	    vaDayNum = (voDiff / (1000 * 60 * 60 * 24))+":"+((voDiff / (1000 * 60 * 60))-((voDiff / (1000 * 60 * 60 * 24))*24) );
	    
    	return vaDayNum;
    }

    static public double getDiffTimes(String paFromDate, String paToDate, String paFromTime, String paToTime){
    	if(paFromDate.length()>8){
    		paFromDate = saveDate(paFromDate);
    	}
    	if(paToDate.length()>8){
    		paToDate = saveDate(paToDate);
    	}
    	if(paFromTime.length()>6){
    		paFromTime = saveTimeNOColon(paFromTime);
    	}
    	if(paToTime.length()>6){
    		paToTime = saveTimeNOColon(paToTime);
    	}
    	int vnYearFrom = Integer.parseInt(paFromDate.substring(0, 4));
    	int vnYearTo = Integer.parseInt(paToDate.substring(0, 4));
    	int vnMonthFrom = Integer.parseInt(paFromDate.substring(4, 6));
    	int vnMonthTo = Integer.parseInt(paToDate.substring(4, 6));
    	int vnDateFrom = Integer.parseInt(paFromDate.substring(6, 8));
    	int vnDateTo = Integer.parseInt(paToDate.substring(6, 8));
    	int vnHourFrom = Integer.parseInt(paFromDate.substring(0, 2));
    	int vnHourTo = Integer.parseInt(paToDate.substring(0, 2));
    	int vnMinFrom = Integer.parseInt(paFromDate.substring(2, 4));
    	int vnMinTo = Integer.parseInt(paToDate.substring(2, 4));
    	long vnDifferentTime = 0;
    	if(vnMonthFrom != vnMonthTo){
        	Date voDayFrom1 = new GregorianCalendar(vnYearFrom, vnMonthFrom, vnDateFrom, vnHourFrom, vnMinFrom).getTime();
    	    Date voDayTo1 = new GregorianCalendar(vnYearFrom, vnMonthFrom, vnDateFrom, 24, 00).getTime();
        	Date voDayFrom2 = new GregorianCalendar(vnYearTo, vnMonthTo, vnDateTo, 00, 00).getTime();
    	    Date voDayTo2 = new GregorianCalendar(vnYearTo, vnMonthTo, vnDateTo, vnHourTo, vnMinTo).getTime();
    	    long vnDifFrom1 = voDayTo1.getTime() - voDayFrom1.getTime();
    	    long vnDifFrom2 = voDayTo2.getTime() - voDayFrom2.getTime();
    	    vnDifferentTime = vnDifFrom1+vnDifFrom2;
    	}else{
        	Date voDayFrom = new GregorianCalendar(vnYearFrom, vnMonthFrom, vnDateFrom, vnHourFrom, vnMinFrom).getTime();
    	    Date voDayTo = new GregorianCalendar(vnYearTo, vnMonthTo, vnDateTo, vnHourTo, vnMinTo).getTime();
    	    vnDifferentTime = voDayTo.getTime() - voDayFrom.getTime();
    	}
    	
	    /** Today's date */
	    double vnNumHour = 0.0;
	    String vaTextHour = "";
	    
	    vaTextHour = (vnDifferentTime / (1000 * 60 * 60))+"."+((vnDifferentTime / (1000 * 60))%60 * 100 /60);
	    vnNumHour = Double.parseDouble(vaTextHour);
	    
	    System.out.println(vaTextHour+" : "+vnNumHour);
	    System.out.println(vnDifferentTime / (1000 * 60 * 60)+".."+(vnDifferentTime / (1000 * 60))%60 * 100 /60+" , "+vnDifferentTime);
	    return vnNumHour;
    }
    
    static public String[] setPriviousBatch(String paMm, String paYy){
        String vaMonth = "";
        String vaYear = "";
        if(paMm.equals("01")){
        	vaMonth = "12";
        	vaYear = ""+(Integer.parseInt(paYy)-1); 
        }else{
        	vaMonth = ""+(Integer.parseInt(paMm)-1);
                if(vaMonth.length()==1){
                	vaMonth = "0"+vaMonth;
                }
                vaYear = paYy;
        }
        String vaRet[] = new String[2];
        vaRet[0] = vaMonth;
        vaRet[1] = vaYear;
        return vaRet;
    }

    static public String[] getNextBatch(String paMm, String paYy){
        String vaMonth = "";
        String vaYear = "";
        if(paMm.equals("12")){
        	vaMonth = "01";
        	vaYear = ""+(Integer.parseInt(paYy)+1); 
        }else{
        	vaMonth = ""+(Integer.parseInt(paMm)+1);
                if(vaMonth.length()==1){
                	vaMonth = "0"+vaMonth;
                }
                vaYear = paYy;
        }
        String vaRet[] = new String[2];
        vaRet[0] = vaMonth;
        vaRet[1] = vaYear;
        return vaRet;
    }

    static public String getThaiYear(String paYear) {
        String vaStrYear = "";
        if (paYear.length()!=4) {
            vaStrYear = paYear; 
        } else {
            vaStrYear = ""+(Integer.parseInt(paYear)+543);
        }
        return vaStrYear;
    }
	static public double getDiffMonth(double vnStartMonth, double vnStartYear, double vnEndMonth, double vnEndYear){
		double vnTotalNum=0;
    	if(vnStartYear==vnEndYear){
        	vnTotalNum=(vnEndMonth-vnStartMonth)+1;
        }else{
        	vnTotalNum = (vnEndYear-vnStartYear)-1 > 1 ? ((vnEndYear-vnStartYear)-1)*12 : 0 ;
        	vnTotalNum = vnTotalNum+((12-vnStartMonth)+1)+vnEndMonth;
        }
    	return vnTotalNum;
	}
    static public String getYearOfNextMonth(String vaMm, String vaYy){
        String vaMonth = "";
        String vaYear = "";
        if(vaMm.equals("12")){
        	vaMonth = "01";
        	vaYear = ""+(Integer.parseInt(vaYy)+1); 
        }else{
        	vaMonth = ""+(Integer.parseInt(vaMm)+1);
                if(vaMonth.length()==1){
                	vaMonth = "0"+vaMonth;
                }
                vaYear = vaYy;
        }
        return vaYear;
    }

    static public String getNextMonth(String vaMm, String vaYy){
        String vaMonth = "";
        String vaYear = "";
        if(vaMm.equals("12")) {
        	vaMonth = "01";
        	vaYear = "" + (Integer.parseInt(vaYy) + 1); 
        } else {
        	vaMonth = "" + (Integer.parseInt(vaMm) + 1);
            if(vaMonth.length() == 1) {
            	vaMonth = "0"+vaMonth;
            }
            vaYear = vaYy;
        }
        return vaMonth;
    }
    
    /**
     * get previous year
     * @param mm recent month
     * @param yy recent year
     * @return previous year
     */
    public static String getYearOfPreviousMonth (String vaMm, String vaYy) {
    	String vaMonth = "";
    	String vaYear = "";
    	if (vaMm.equals("01")) {
    		vaMonth = "12";
    		vaYear = "" + (Integer.parseInt(vaYy) - 1);
    	} else {
    		vaMonth = "" + (Integer.parseInt(vaMm) - 1);
    		if (vaMonth.length() == 1) {
    			vaMonth = "0" + vaMonth;
    		}
    		vaYear = vaYy;
    	}
    	return vaYear;
    }
    
    /**
     * get previous month
     * @param mm recent month
     * @param yy recent year
     * @return previous month
     */
    public static String getPreviousMonth (String vaMm, String vaYy) {
    	String vaMonth = "";
    	String vaYear = "";
    	if (vaMm.equals("01")) {
    		vaMonth = "12";
    		vaYear = "" + (Integer.parseInt(vaYy) - 1);
    	} else {
    		vaMonth = "" + (Integer.parseInt(vaMm) - 1);
    		if (vaMonth.length() == 1) {
    			vaMonth = "0" + vaMonth;
    		}
    		vaYear = vaYy;
    	}
    	return vaMonth;
    }
    
    static public String setNotMatchDay(String paYyyyMmDd){
    	String vaRet = "";
    	if(paYyyyMmDd.length()!= 8){
    		vaRet = "";
    	}else{
        	int vaDate=Integer.parseInt(paYyyyMmDd.substring(6,8));
        	if(vaDate<15)vaDate=14;
        	if(vaDate>15)vaDate=16;
        	vaRet = paYyyyMmDd.substring(0,6)+String.valueOf(vaDate);
    	}
    	return vaRet;
    }
    
    static public String setTimeIncrement(String paDate,String paHhMmSs,int pnDiff,String paIsIncrement){
    DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    String strdate = null;
    
    	try {
			Date parsed = df.parse(paDate+paHhMmSs);
			  Calendar calendar = GregorianCalendar.getInstance(); 
			  calendar.setTime(parsed); 
    		if(paIsIncrement.equals("Y")){
    			calendar.add(Calendar.MINUTE,(pnDiff));
	    	}else{
	    		calendar.add(Calendar.MINUTE,-(pnDiff));
	    	}
    		 
			 strdate = sdf.format(calendar.getTime());
    		 } catch (ParseException e) {
					e.printStackTrace();
			}
    	return strdate;
    }
    
    public static String getMonthName(int pnMonth){
    	Locale.setDefault(new Locale("th","TH")); 	
    	return new DateFormatSymbols().getMonths()[pnMonth-1];
    }
    
    public static String checkMonth(int pnMonth){
    	int vnTempMonth = pnMonth + 1;
    	String vaResult = "";
    	if (vnTempMonth < 13 ){
    		if (vnTempMonth < 10){
        		vaResult = "0" + String.valueOf(vnTempMonth); 
        	} else{
        		vaResult = String.valueOf(vnTempMonth);
        	}
    	} else{
    		vaResult = "0"+String.valueOf(1);
    	}
    	return vaResult;
    }   
    
    public static int checkYear(int vnMonth,int vnYear){
    	int vnTempYear = 0;
    	if ((vnMonth + 1) > 12){
    		vnTempYear = vnYear + 1; 		
    	} else{
    		vnTempYear = vnYear;
    	}
    	return vnTempYear;
    }
    
    public static String paddingMonth(int vnMonth){
    	String vnTempMonth = "";
    	if (vnMonth < 10){
    		vnTempMonth = "0"+String.valueOf(vnMonth);
    	} else{
    		vnTempMonth = String.valueOf(vnMonth);
    	}
    	return vnTempMonth;
    }
    
    /**
     * get month's name by JDate.getDate() or Date which is saved into database
     * @param paDate String format: "yyyymmdd"
     * @return month's name
     */
    public static String getMonthNameByDate(String paDate){
    	String tmp = JDate.showDate(paDate);
		String[] parts = tmp.split("/");
		int vnMonth = Integer.parseInt(parts[1]);
    	Locale.setDefault(new Locale("th","TH")); 	
    	return parts[0] + " " + new DateFormatSymbols().getMonths()[vnMonth-1] + " " + parts[2];
    }
    
//    public static String checkBackTimeDate(int pnSiteId){
//		// Check Back Time 
//		Database db = new Database();
//		BackTimeDAO voBackTimeDAO = new BackTimeDAO(db);
//		String vaReceiveDateToDB = JDate.getDate();	
//		try {
//			BackTime voBackTime = voBackTimeDAO.getExpireAndBackTimeDate(pnSiteId); 
//			if ( voBackTime != null){
//				String vaExpireDate = voBackTime.getVaExpireDate();
//				String vaBackTimeDate = voBackTime.getVaBackTimeDate();
//				Locale.setDefault(new Locale("th","TH"));
//				DateFormat df = new SimpleDateFormat("yyyyMMdd");
//				Date exprieDate = df.parse(vaExpireDate);
//				String vaCurrent = df.format(new Date());
//				Date current = df.parse(vaCurrent);
//				if ( exprieDate.after(current) || exprieDate.equals(current) ){
//					// "Is Not Expire..."
//					vaReceiveDateToDB = vaBackTimeDate;
//				} else {
//					// "Is Expire..."
////					vaReceiveDateToDB = JDate.getDate();
//				}
//			}
//
//		} catch (Exception e) {
//			System.out.println(e.getMessage());
//		}
//		db.close();
//		return vaReceiveDateToDB; 	
//    }
    
}